package com.taylor.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taylor.seckill.mapper.OrderMapper;
import com.taylor.seckill.pojo.Order;
import com.taylor.seckill.pojo.SeckillGoods;
import com.taylor.seckill.pojo.SeckillOrder;
import com.taylor.seckill.pojo.User;
import com.taylor.seckill.service.IOrderService;
import com.taylor.seckill.service.ISeckillGoodsService;
import com.taylor.seckill.service.ISeckillOrderService;
import com.taylor.seckill.util.RedisUtil;
import com.taylor.seckill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author taylor
 * @since 2021-04-11
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    ISeckillGoodsService seckillGoodsService;

    @Autowired
    ISeckillOrderService seckillOrderService;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    OrderMapper orderMapper;

    @Transactional
    @Override
    public Order doSeckill(User user, GoodsVo goods) {

        //秒杀商品表减库存
        SeckillGoods seckillGoods = seckillGoodsService.getOne(new QueryWrapper<SeckillGoods>().eq("goods_id", goods.getId()));
        seckillGoods.setStockCount(seckillGoods.getStockCount()-1);
//        seckillGoodsService.updateById(seckillGoods);
        UpdateWrapper<SeckillGoods> updateWrapper = new UpdateWrapper<>();
//        updateWrapper.set("stock_count",seckillGoods.getStockCount()).
//                eq("id",seckillGoods.getId()).
//                gt("stock_count",0);

        updateWrapper.setSql("stock_count=stock_count-1").
                eq("goods_id",goods.getId()).
                gt("stock_count",0);
        boolean flag = seckillGoodsService.update(updateWrapper);
        if (!flag) {
            return null;
        }
        //生成订单
        Order order = new Order();
        order.setGoodsId(goods.getId());
        order.setUserId(user.getId());
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(goods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        orderMapper.insert(order);
        //生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setGoodsId(goods.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setUserId(user.getId());

        seckillOrderService.save(seckillOrder);
        redisUtil.set("order:"+user.getId()+":"+goods.getId(),seckillOrder);
        return order;
    }
}
